<template>
  <div>
    <div
    style="width: 1920px; overflow: auto; height: 1080px"
    id="myMap"
    ref="myMap"
  ></div>
  <div ref="overlay" class="overlay">
      <div class="overlay-content"></div>
    </div>
  </div>
</template>
 
<style>
</style>
 
<script lang="ts">
import "ol/ol.css";
import Map from "ol/Map";
import View from "ol/View";
import ImageLayer from "ol/layer/Image";
import { ImageStatic } from "ol/source";
import { Projection } from "ol/proj";
import { getCenter } from "ol/extent";
import * as olInteraction from "ol/interaction";
import DragRotateAndZoom from "ol/interaction/DragRotateAndZoom";
import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";
import { LineString, Point, Polygon } from "ol/geom";
import { createStringXY } from "ol/coordinate";
import { FullScreen, MousePosition } from "ol/control";
import { defaults as defaultControls } from "ol/control";
import Zoom from "ol/control/Zoom";
import { Icon, Style, Text, Fill, Stroke, Circle } from "ol/style";
// import Fill from "ol/style/Fill";
// import Stroke from "ol/style/Stroke";
import Feature from "ol/Feature";

import { Draw, Select, Snap, Modify } from "ol/interaction";

// import * as turf from "@turf/turf";

const img_icon = require("../assets/published.png");
const icon_1 = require("../assets/icon_1.png");

import { getVectorContext } from "ol/render";

import MouseWheelZoom from "ol/interaction/MouseWheelZoom";

export default {
  name: "olMap",
  data() {
    return {
      map: null, // 地图
      imgx: 1920, // 当前地图宽
      imgy: 1080, // 当前地图高
      // 图标管理器
      iconLayer: "",
      // 鼠标坐标管理器
      mousePositionControl: "",
      // 鼠标悬浮图层
      hoverFeature: null,
      //   vectorSource: null,
      // 图标集合
      featureList: [],
      // 轮询显示图标设备名称定时器
      showDeviceTimer: null,
      // 设备集合
      deviceList: [
        {
          x: 400,
          y: 500,
          zIndex: 2,
          imgUrl: require("../assets/alarm_car.png"),
          deviceName: "精密空调",
          deviceId: 1,
          alarmFlag: false,
        },
        {
          x: 430,
          y: 320,
          zIndex: 2,
          imgUrl: require("../assets/alarm_car.png"),
          deviceName: "办公室门禁",
          deviceId: 2,
          alarmFlag: false,
        },
        {
          x: 200,
          y: 600,
          // 层级
          zIndex: 2,
          imgUrl: require("../assets/alarm_car.png"),
          deviceName: "消防烟感1",
          deviceId: 3,
          alarmFlag: true,
        },
        {
          x: 620,
          y: 600,
          zIndex: 2,
          imgUrl: require("../assets/alarm_car.png"),
          deviceName: "消防烟感2",
          deviceId: 4,
          alarmFlag: true,
        },
      ],
      // 绘制区域
      isDraw: true, // 是否绘制
      draw: null,
      source: null,
      vector: null,
      styles: [
        new Style({
          stroke: new Stroke({
            color: "#3DE8FF",
            width: 2,
          }),
          fill: new Fill({
            color: "rgba(61, 232, 255, 0.3)",
          }),
        }),
      ],
      persons: [],
      polygon: [],
      polygonPersons: [],
      features: [],
      feature: null,
      vectorSource: new VectorSource(),
      timer: null,

      polygonSource: null,
      polygonLayer: null,

      select: null,
      modify: null,

      //   轨迹回放
      textContent: "播放",
      animating: false, // 动画是否开始
      speed: 2, // 速度
      now: null, // 当前时间
      vectorLayer: null, // 矢量图层
      routeCoords: [], // 数组点集合(线路坐标)
      routeLength: 0, // 集合点的数量长度
      routeFeature: null, // 画线
      geoMarker: null, // 移动标记
      startMarker: null, // 开始标记
      endMarker: null, // 结束标记
      stylesTrack: {
        route: new Style({
          // 线的样式
          stroke: new Stroke({
            width: 6,
            color: [61, 232, 255, 1],
          }),
        }),
        // icon: new Style({
        //   // 默认icon样式
        //   image: new Circle({
        //     radius: 7,
        //     fill: new Fill({ color: "red" }),
        //     stroke: new Stroke({
        //       color: "white",
        //       width: 2,
        //     }),
        //   }),
        // }),
        geoMarker: new Style({
          // 移动人物的图标样式
          image: new Icon({
            anchor: [0.5, 0.8], // 居中
            // anchorOrigin: 'top-right',
            // anchorXUnits: 'fraction',
            // anchorYUnits: 'pixels',
            // offsetOrigin: 'top-right',
            // offset:[0,10],
            scale: 0.9, // 图标缩放比例
            opacit: 1, // 透明度
            src: require("@/assets/vector.png"),
          }),
        }),
        start: new Style({
          // 设置开始标记样式
          image: new Icon({
            anchor: [0.5, 1],
            src: require("@/assets/published.png"),
          }),
        }),
        end: new Style({
          // 设置结束标记样式
          image: new Icon({
            anchor: [0.5, 1],
            src: require("@/assets/untreated.png"),
          }),
        }),
      },
      progress: 0,
    };
  },

  mounted() {
    this.initMap();

    this.persons = [
      { id: 1, name: "点-1", x: 1550, y: 900, z: 0 },
      { id: 2, name: "点-2", x: 725.32, y: 565.88, z: 0 },
      { id: 3, name: "点-3", x: 643.24, y: 503.96, z: 0 },
    ];
  },
  methods: {
    initMap() {
      this.imgy = this.$refs.myMap.offsetHeight;
      this.imgx = this.$refs.myMap.offsetWidth;
      let extent = [0, 0, this.imgx, this.imgy]; // 获取图片的宽高
      console.log("extent", getCenter(extent));

      // [minx, miny, maxx, maxy].
      let projection = new Projection({
        code: "xkcd-image",
        units: "pixels",
        extent: extent,
      });
      //线的图层
      this.polygonSource = new VectorSource({ wrapX: false });
      this.polygonLayer = new VectorLayer({
        source: this.polygonSource,
      });
      // 添加矢量层
      this.vectorLayer = new VectorLayer({
        source: new VectorSource(),
      });

      this.map = new Map({
        target: "myMap",
        // shift控制旋转
        interactions: olInteraction
          .defaults({
            mouseWheelZoom: false,
            doubleClickZoom: false,
            dragPan: false,
          })
          .extend([
            //   new DragRotateAndZoom(),
          ]),
        layers: [
          new ImageLayer({
            source: new ImageStatic({
              url: require("../assets/map2.png"), // 静态地图
              projection: projection,
              imageExtent: extent,
            }),
          }),
          this.polygonLayer,
          this.vectorLayer,
        ],
        // 缩放等级zoom当前缩放程度，maxZoom最大缩放程度
        view: new View({
          projection: projection,
          center: getCenter(extent),
          // 当前缩放倍数
          zoom: 2.9,
          // 最大缩放倍数
          maxZoom: 7,
          // 最小缩放倍数
          minZoom: 1,
        }),
        controls: defaultControls({
          rotate: true,
          zoom: false,
        }).extend([
          //   new FullScreen({
          //     tipLabel: "全屏",
          //   }),
          //   new Zoom({
          //     zoomInTipLabel: "放大",
          //     zoomOutTipLabel: "缩小",
          //   }),
        ]),
      });
      console.log("this.map", this.map);

      //   this.map.on("wheel",  (evt) => {
      //     console.log('loadstart', evt);

      //   });
      //   this.map.on("loadend",  () => {
      //     console.log('loadend');

      //   });
      // this.map.getControls().clear()
      this.$emit("map", this.map);

    //   this.mapOver();
      this.mapClick();
      this.mapResolution();
      this.addMousePosition();
      //   this.addInteractionLine();
      //   this.drawArea();
      //   this.initDraw();
      //   this.drawPolygon();

      //   是添加多边形相关--------start
      this.source = new VectorSource({ wrapX: false });
      this.vector = new VectorLayer({
        source: this.source,
        style: this.styles,
      });
      this.map.addLayer(this.vector);
      //   是添加多边形相关--------end
      // 修改旋转鼠标悬浮tip
      //   document.getElementsByClassName(
      //     "ol-rotate-reset"
      //   )[0].attributes.title.nodeValue = "重置旋转";
    },
    // 添加鼠标悬浮地图中坐标
    addMousePosition() {
      this.removeMousePosition();
      this.mousePositionControl = new MousePosition({
        coordinateFormat: function (e) {
          // 这里格式化成 X: **  Y: **
          // 将坐标保留4位小数位，并转换为字符串
          let stringifyFunc = createStringXY(4);
          let str = stringifyFunc(e);
          return (
            "X: " + str.split(",")[0] + "&nbsp;" + " Y: " + str.split(",")[1]
          );
        },
        // projection: "EPSG:4326", // 和地图坐标系保持一致
        className: "custom-mouse-position", // css类名
        target: document.getElementById("mousePosition"), // 显示位置鼠标坐标位置DOM
      });
      // 添加控制控件到地图上即可
      this.map.addControl(this.mousePositionControl);
    },
    // 移除鼠标位置
    removeMousePosition() {
      if (this.mousePositionControl) {
        // 移除
        this.map.removeControl(this.mousePositionControl);
        this.mousePositionControl = null;
      }
    },
    // 添加图标
    addDevicePoint(item) {
      // 设置图片位置
      const iconFeature = new Feature({
        geometry: new Point([item.x, item.y]),
      });
      // 设置样式，这里使用图片
      iconFeature.setStyle([
        new Style({
          image: new Icon({
            // 指定锚 x 值的单位。的值'fraction'表示 x 值是图标的一部分。的值'pixels'表示以像素为单位的 x 值。
            anchorXUnits: "fraction",
            // 左下角为原点
            anchorOrigin: "bottom-left",
            anchorYUnits: "fraction",
            anchor: [0.5, 0],
            // src: item.imgUrl
            src: item.imgUrl,
          }),
          zIndex: item.zIndex,
        }),
        new Style({
          text: new Text({
            text: "",
            font: "14px Microsoft YaHei",
            offsetY: -15,
            offsetX: 15,
            padding: [5, 10, 5, 15],
            textAlign: "left",
            backgroundFill: new Fill({
              // eslint-disable-next-line no-constant-condition
              color: item.alarmFlag
                ? "rgba(249, 88, 87, 0.5)"
                : "rgba(0,111,255,0.5)", //提示背景色
            }),
            fill: new Fill({
              color: "#fff",
            }),
          }),
          zIndex: item.zIndex,
        }),
      ]);
      // 给图层设置设备图标name和id属性，用作独立 区分
      iconFeature.name = item.deviceName;
      iconFeature.id_ = item.deviceId;
      // 将图片Feature添加到Source
      this.featureList.push(iconFeature);
    },
    // 鼠标悬停
    mapOver() {
      const _this = this;
      this.map.on("singleclick", (evt) => {
        // 手指效果
        var pixel = _this.map.getEventPixel(evt.originalEvent);
        var hit = _this.map.hasFeatureAtPixel(pixel);
        // 高亮区域取消手指效果
        const hoverFeature = _this.map.getFeaturesAtPixel(pixel);
        this.$refs.myMap.style.cursor =
          hit && hoverFeature.length >= 1 ? "pointer" : "";
        var feature = _this.map.forEachFeatureAtPixel(
          evt.pixel,
          function (feature) {
            return feature;
          }
        );
        if (feature !== undefined) {
          if (!Array.isArray(feature.style_)) return;
          this.restoreDeviceText();
          console.log("feature", feature);
          console.log("feature", feature.style_);
          // 当移入图标时
          // 鼠标移入更改值
          feature.style_[1].text_.text_ = feature.name;
          // 鼠标移入更改图标层级为优先级
          feature.style_[0].zIndex_ = 3;
          feature.style_[1].zIndex_ = 3;
          // 设置当前悬浮图层
          this.hoverFeature = feature;
          this.hoverFeature.changed();

          // 停掉轮询定时器
          clearInterval(this.showDeviceTimer);
          this.showDeviceTimer = null;
        } else {
          // 当移出图标时
          if (this.hoverFeature) {
            // 鼠标移入更改图标层级为优先级
            this.hoverFeature.style_[0].zIndex_ = 1;
            this.hoverFeature.style_[1].zIndex_ = 1;
            // 重启轮询定时器
            if (!this.showDeviceTimer) {
              // 将设备tip标签值设置为空
              this.restoreDeviceText();
              this.pollShowDeviceText();
            }
          }
        }
      });
    },
    // 监听地图点击事件
    mapClick() {
      var _this = this;
      this.map.on("singleclick", (evt) => {
        console.log("鼠标点击", evt);

        var feature = _this.map.forEachFeatureAtPixel(
          evt.pixel,
          function (feature) {
            return feature;
          }
        );

        console.log("feature:", feature);
      });
    },
    // 监听地图缩放
    mapResolution() {
      this.map.getView().on("change:resolution", (evt) => {
        console.log("缩放了！", evt);
        console.log("当前zoom：" + this.map.getView().getZoom());
        if (this.map.getView().getZoom() == 7) {
          this.map.getView().setResolution(1);
        }
      });
    },
    // 轮询显示图标设备名称
    pollShowDeviceText() {
      let FeatrueList = this.iconLayer.getSource().getFeatures();
      let allSize = FeatrueList.length - 1;
      let currentSize = 0;
      /* start
       * 这里必须初始化一遍hoverFeature,不然在定时器延时等待过程中会出现拿不到hoverFeature的情况
       * */
      if (this.hoverFeature) {
        this.restoreDeviceText();
      }
      this.hoverFeature = FeatrueList[currentSize];
      this.hoverFeature.style_[1].text_.text_ = this.hoverFeature.name;
      this.hoverFeature.changed();
      currentSize++;
      /* end * */
      this.showDeviceTimer = setInterval(() => {
        if (this.hoverFeature) {
          this.restoreDeviceText();
        }
        if (currentSize > allSize) {
          currentSize = 0;
        }
        this.hoverFeature = FeatrueList[currentSize];
        this.hoverFeature.style_[1].text_.text_ = this.hoverFeature.name;
        this.hoverFeature.changed();
        currentSize++;
      }, 3000);
    },
    // 将设备tip标签值设置为空
    restoreDeviceText() {
      this.hoverFeature.style_[1].text_.text_ = "";
      this.hoverFeature.changed();
      this.hoverFeature = null;
    },
    // 添加线段
    addInteractionLine() {
      const points = [
        [480, 630],
        [900, 600],
        [200, 100],
        [950, 100],
      ];
      let style = new Style({
        stroke: new Stroke({
          color: "#3DE8FF",
          width: 3,
        }),
      });
      function getStyle(resolution) {
        return [
          new Style({
            image: new Icon({
              src: require("../assets/processing.png"),
              scale: 1,
            }),
          }),
        ];
      }
      let featureLine = new Feature({
        geometry: new LineString(points),
        // style: getStyle
      });
      console.log(
        'feature.get("geometry").getCoordinates();',
        featureLine.get("geometry").getCoordinates()
      );

    //   featureLine.setStyle(
    //     new Style({
    //       stroke: new Stroke({
    //         color: "#3DE8FF",
    //         width: 3,
    //       }),
    //     })
    //   );
      let features = [featureLine];

      const coords = featureLine.get("geometry").getCoordinates();

      for (var i = 0; i < coords.length; i++) {
        const point = new Feature({
          geometry: new Point(coords[i]),
        });
        const style = new Style({
          image: new Icon({
            // 指定锚 x 值的单位。的值'fraction'表示 x 值是图标的一部分。的值'pixels'表示以像素为单位的 x 值。
            anchorXUnits: "fraction",
            // 左下角为原点
            anchorOrigin: "bottom-left",
            anchorYUnits: "fraction",
            anchor: [-0.1, -0,2],
            // scale: 0.8,
            src: require("@/assets/icon_1.png"),
          }),
          zIndex: 2,
        });
        const labelStyle = new Style({
          text: new Text({
            text: "途径点位：" + i,
            // text:  ['foo', 'bold 10px sans-serif', ' bar', 'italic 10px sans-serif', ' baz', ''],
            font: "14px Microsoft YaHei",
            offsetY: -13,
            offsetX: 63,
            padding: [5, 10, 0, 43],
            textAlign: "left",
            backgroundFill: new Fill({
              color: "rgba(3, 45, 69, 1)",
            }),
            fill: new Fill({
              color: "#fff",
            }),
          }),
          zIndex: 1,
        });
        point.setStyle([style, labelStyle,]);
        point.id = "test666" + i;
        point.name = "测试name" + i;
        features.push(point)
      }

      let source = new VectorSource({
        features: features,
      });
      const styleFunction = (feature) => {
        var styles = [];

        styles.push(
          new Style({
            stroke: new Stroke({
              color: "#3DE8FF",
              width: 4,
            }),
          })
        );

        var _coords = feature.get("geometry").getCoordinates();
        console.log("_coords", _coords);

        for (var i = 0; i < _coords.length; i++) {
          let point = new Point(_coords[i]);
          styles.push(
            new Style({
              geometry: point,
                image: new Circle({
                    radius: 7,
                    fill: new Fill({
                        color: '#3DE8FF'
                    }),
                    stroke: new Stroke({
                        color: '#3DE8FF',
                        width: 2
                    })
                })
            //   image: new Icon({
            //     // 指定锚 x 值的单位。的值'fraction'表示 x 值是图标的一部分。的值'pixels'表示以像素为单位的 x 值。
            //     anchorXUnits: "fraction",
            //     // 左下角为原点
            //     anchorOrigin: "bottom-left",
            //     anchorYUnits: "fraction",
            //     anchor: [0.5, 0],
            //     // scale: 0.8,
            //     src: icon_1,
            //   }),
            })
          );
        }
        console.log("styles", styles);

        return styles;
      };
      //   source.addFeature(featureLine);
      let layer = new VectorLayer({
        source,
        style: styleFunction,
      });
      //   layer.setSource(source);
      this.map.addLayer(layer);
    },

    /**
     * 添加图标
     */
    addDevice() {
      this.deviceList.forEach((item) => {
        this.addDevicePoint(item);
      });
      const vectorSource = new VectorSource();
      this.iconLayer = new VectorLayer({
        source: vectorSource,
      });
      // 将图标数组添加到图层中
      console.log("featureList", this.featureList);

      this.iconLayer.getSource().addFeatures(this.featureList);
      // 添加图层
      this.map.addLayer(this.iconLayer);
      this.pollShowDeviceText();
    },

    //画多边形
    drawPolygon() {
      //  最后要把polygon显示出来需要这样一个流程：polygon封装到Feature --> feature添加到source --> 通过source创建vector layer --> 把layer添加到map上。
      let pointArr = [
        [
          [[986957.12], [215578.12]],
          [[989763.12], [213860.12]],
          [[987415.12], [212008.12]],
          [[986957.12], [215578.12]],
        ],
      ];
      const points = [
        [
          [1172.5256387165857, 1021.2124048881539],
          [1712.1365011095697, 973.4826971580619],
          [1614.0254352199363, 506.7922215749405],
          [1173.8514639313105, 675.1720238449872],
          [1172.5256387165857, 1021.2124048881539],
        ],
      ];
      //下边来添加一线feature
      var feature = new Feature({
        type: "Polygon",
        geometry: new Polygon(
          points // 线的坐标
        ),
      });
      let lineStyle = new Style({
        fill: new Fill({
          color: "rgba(61, 232, 255, 0.3)",
        }),
        stroke: new Stroke({
          color: "#3DE8FF",
          width: 3,
        }),
      });
      // 添加线的样式
      feature.setStyle(lineStyle);
      // 添加线的fature
      this.polygonSource.addFeature(feature);
    },

    // ------------------------------------------------------------------------------------
    // 绘制相关
    // 点
    setFeature() {
      let that = this;
      that.features = [];
      that.vectorSource.clear();
      that.persons.map((item) => {
        that.feature = new Feature({
          geometry: new Point([item.x, item.y]),
          name: item.name,
        });
        // 设置Feature的样式，使用小旗子图标
        that.feature.setStyle(
          new Style({
            image: new Icon({
              anchor: [0, 1],
              src: img_icon,
            }),
            text: new Text({
              // 位置
              textAlign: "center",
              // 基准线
              textBaseline: "middle",
              // 文字样式
              font: "normal 20px 微软雅黑",
              // 文本内容
              text: item.name,
              // 文本填充样式（即文字颜色）
              fill: new Fill({ color: "#aa3300" }),
              stroke: new Stroke({ color: "#ffcc33", width: 2 }),
            }),
          })
        );
        that.features.push(that.feature);
      });
      that.vectorSource.addFeatures(that.features);
    },

    // 开始绘制多边形
    drawStart(type = "Polygon") {
      let that = this;
      if (this.isDraw) {
        this.isDraw = false;
        this.draw = new Draw({
          source: this.source,
          type: type,
        });
        this.map.addInteraction(this.draw);

        this.draw.on("drawend", function (evt) {
          that.drawingEnd(evt);
        });
      } else {
        this.source.clear();
        this.map.removeInteraction(this.draw);
        this.isDraw = true;
        this.polygon = [];
        this.polygonPersons = [];
      }
    },

    // 构建多边形结束
    drawingEnd(evt) {
      console.log("drawEnd", evt);

      let that = this;
      const geo = evt.feature.getGeometry();
      const t = geo.getType();
      if (t === "Polygon") {
        // 获取坐标点
        const points = geo.getCoordinates();
        console.log("points", points);

        this.selectInit();
        this.modifyInit();
        this.snapInit();

        points[0].map((item) => {
          that.polygon.push({ lng: item[0], lat: item[1] });
        });
        for (let i = 0; i < this.persons.length; i++) {
          let boxFlag = this.isRegion(
            this.persons[i].x,
            this.persons[i].y,
            this.polygon
          );
          if (boxFlag) {
            this.polygonPersons.push(this.persons[i]);
          }
        }
        this.$message({
          type: "success",
          message: `区域内有${this.polygonPersons.length}人`,
        });
        console.warn(
          this.polygonPersons,
          `区域内有${this.polygonPersons.length}人`
        );
        this.map.removeInteraction(this.draw); // 移除绘制
      }
    },

    // 验证点是否在区域内
    isRegion(lon, lat, aPoints) {
      let num = 0,
        iCount;
      let dLon1, dLon2, dLat1, dLat2, dLon;
      if (aPoints.length < 3) return false;
      iCount = aPoints.length;
      for (let i = 0; i < iCount; i++) {
        if (i == iCount - 1) {
          dLon1 = aPoints[i].lng;
          dLat1 = aPoints[i].lat;
          dLon2 = aPoints[0].lng;
          dLat2 = aPoints[0].lat;
        } else {
          dLon1 = aPoints[i].lng;
          dLat1 = aPoints[i].lat;
          dLon2 = aPoints[i + 1].lng;
          dLat2 = aPoints[i + 1].lat;
        }
        if ((lat >= dLat1 && lat < dLat2) || (lat >= dLat2 && lat < dLat1)) {
          if (Math.abs(dLat1 - dLat2) > 0) {
            dLon = dLon1 - ((dLon1 - dLon2) * (dLat1 - lat)) / (dLat1 - dLat2);
            if (dLon < lon) num++;
          }
        }
      }
      if (num % 2 != 0) return true;
      return false;
    },
    //重新绘制 清楚绘制
    clearPolygon() {
      this.draw.removeLastPoint();
    },
    //捕捉交互必须在“修改”和“绘制”交互之后添加
    //以便首先启动其地图浏览器事件处理程序。其处理程序
    //负责捕捉。
    snapInit() {
      const snap = new Snap({
        source: this.vector.getSource(),
      });
      this.map.addInteraction(snap);
    },
    selectInit() {
      this.select = new Select();
      this.map.addInteraction(this.select);
      this.select.setActive(true);
    },
    modifyInit() {
      this.modify = new Modify({
        features: this.select.getFeatures(),
      });
      this.map.addInteraction(this.modify);
      this.modify.setActive(true);
      this.modify.on("modifyend", function (e) {
        var features = e.features.array_;
        console.log("modifyend", e);
        console.log("modifyend", features);

        const geo = features[0].getGeometry();
        // 获取坐标点
        const points = geo.getCoordinates();
        console.log("points", points);
      });
    },

    // 轨迹回放
    moveFeature(event) {
      console.log("moveFeature");

      let vectorContext = getVectorContext(event);
      let frameState = event.frameState;

      if (this.animating) {
        let elapsedTime = frameState.time - this.now;
        let index = Math.round((this.speed * elapsedTime) / 1000);
        this.progress =
          Math.floor(
            ((100 / this.routeLength) * (this.speed * elapsedTime)) / 1000
          ) + "%";
        if (index >= this.routeLength) {
          this.progress = "100%";
          this.stop(true);
          return;
        }
        let currentPoint = new Point(this.routeCoords[index]); // 当前点
        let feature = new Feature(currentPoint);
        vectorContext.drawFeature(feature, this.stylesTrack.geoMarker);
      }
      this.map.render();
    },

    // 运动轨迹开关
    toggle() {
      if (this.textContent === "重新播放") {
        this.progress = 0;
        this.stop(false);
      } else {
        console.log("开始");
        this.start();
      }
    },

    // 开始动画
    start() {
      if (this.animating) {
        this.stop(false);
      } else {
        console.log("开始动画");

        // hide geoMarker
        this.animating = true;
        this.textContent = "重新播放";
        this.now = new Date().getTime(); // 开始时的时间
        // this.geoMarker.setStyle(null);
        // 设置显示范围
        // this.map.getView().setCenter(center)
        this.vectorLayer.on("postrender", this.moveFeature);
        this.map.render();
      }
    },

    // 停止
    stop(ended) {
      this.textContent = "开始播放";
      this.animating = false;
      // if animation cancelled set the marker at the beginning
      let ii = ended ? this.routeLength - 1 : 0;
      let coord = this.routeCoords[ii];
      this.geoMarker.setGeometry(new Point(coord));
      // this.geoMarker.setStyle(this.createLabelStyle(img)); // 设置走完最后一个点是否展示
      // remove listener // 删除侦听器
      this.vectorLayer.un("postrender", this.moveFeature);
    },

    // 设置坐标样式
    createLabelStyle(img) {
      return new Style({
        image: new Icon({
          anchor: [0.5, 0.8], // 居中
          // anchorOrigin: 'top-right',
          // anchorXUnits: 'fraction',
          // anchorYUnits: 'pixels',
          // offsetOrigin: 'top-right',
          // offset:[0,10],
          scale: 0.5, // 图标缩放比例
          opacit: 1, // 透明度
          src: img, // 图标的url
        }),
      });
    },

    // 获取基站列表
    getTrack() {
      // 获取接口返回数据
      //   let res = [
      //     [256.83593750000006, 370.91015624999994],
      //     [261.71875000000006, 425.59765624999994],
      //     [253.90625000000006, 469.54296875],
      //     [338.86718750000006, 488.09765625],
      //     [406.25000000000006, 488.09765625],
      //     [471.67968750000006, 488.09765625],
      //     [544.9218750000001, 471.49609375],
      //     [547.8515625000001, 416.80859374999994],
      //     [542.9687500000001, 366.02734374999994],
      //   ];
      let res = [
        [480, 630],
        [900, 600],
        [500, 300],
        [200, 100],
        [950, 100],
      ];
      this.routeCoords = res.map((d) => {
        return (d = [d[0], d[1]]);
      });
      console.log("routeCoords", this.routeCoords);

      this.routeLength = this.routeCoords.length;

      // 画线
      this.routeFeature = new Feature(new LineString(this.routeCoords));
      this.routeFeature.setStyle(this.stylesTrack.route);

      // 标记
      this.geoMarker = new Feature(new Point(this.routeCoords[0]));
      this.geoMarker.setStyle(this.stylesTrack.geoMarker);
      // 开始点
      this.startMarker = new Feature(new Point(this.routeCoords[0]));
      this.startMarker.setStyle(this.stylesTrack.start);
      // 结束点
      this.endMarker = new Feature(
        new Point(this.routeCoords[this.routeLength - 1])
      );
      this.endMarker.setStyle(this.stylesTrack.end);

      // 运动集合展示在矢量图上
      this.vectorLayer
        .getSource()
        .addFeatures([
          this.routeFeature,
          this.geoMarker,
          this.startMarker,
          this.endMarker,
        ]);
      this.map.render();
      //   this.moveFeature()
      this.toggle();
    },
    // 轨迹回放结束
    test() {
        console.log('layer', this.map.getLayers().getArray());
        
    }
  },

  destroyed() {
    clearInterval(this.showDeviceTimer);
    this.showDeviceTimer = null;
  },
};
</script>
 
<style scoped>
/* /deep/ .ol-rotate { */
/* 设置地图旋转回正按钮位置，避免与全屏按钮重叠*/
/* right: 3em; */
/* } */
.custom-mouse-position {
  color: #42b985 !important;
}
.overlay {
    position: absolute;
    background-color: rgba(117, 140, 240, 0.596);
    border: 1px solid #15377c;
    padding: 10px;
    border-radius: 20px;
    min-width: 100px;
  }
  .overlay-content {
    font-size: 14px;
  }

</style>